package qs.openxt.libs.progress;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;

import qs.openxt.libs.R;

public class DownloadDialogProgress {
	private Dialog dialog = null;
	private Context context = null;

	private TextView tv_tips = null;
	private TextView tv_down = null;
	private ProgressBar mProgress;
	private int progress;
	private static final int DOWNLOAD = 1;

	public DownloadDialogProgress(Context context){
		this.context = context;
	}
	
	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case DOWNLOAD:
				tv_down.setText(progress + "%");
				mProgress.setProgress(progress);
				break;
			default:
				break;
			}
		};
	};
	
	public void setProgress(int progress){
		this.progress = progress;
		
		mHandler.sendEmptyMessage(DOWNLOAD);
	}
	
	public void show(){
		if(dialog != null)
			return;
		
		dialog = new Dialog(context, R.style.ProgressDialog);
		View view = LayoutInflater.from(context).inflate(R.layout.download_dialog_progress, null);
		tv_tips = (TextView) view.findViewById(R.id.tv_tips);
		tv_tips.setText(context.getString(R.string.framework_d_loading));
		tv_down = (TextView) view.findViewById(R.id.tv_down);
		tv_down.setText("0%");
		mProgress = (ProgressBar) view.findViewById(R.id.pb_down);
		mProgress.setProgress(1);
		mProgress.setMax(100);
		dialog.setContentView(view);
		dialog.setOnCancelListener(new OnCancelListener() {
			public void onCancel(DialogInterface dialog) {
				close();
			}
		});
		dialog.setCanceledOnTouchOutside(false);
		dialog.setCancelable(false);
		dialog.show();
	}
	
	public void close(){
		if(dialog == null)
			return;
		try {
			dialog.dismiss();
			dialog = null;
		} catch (Exception e) {
		}
	}
}
